package login;

import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import java.io.PrintWriter;

import java.io.BufferedReader;
import java.io.FileReader;
import bean.Message;

@WebServlet(name = "Login_C",urlPatterns = {"/Login_C"})
public class Login_C extends HttpServlet {
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    protected void login_check(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {
        System.out.println("22222222222222222222222222222222222222");
        String loginname = req.getParameter("loginname");
        String loginpassword = req.getParameter("loginpassword");
        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();
        boolean flag=false;
        Message message=null;
        //判断登录信息是否存在
        try {
            System.out.println("11111111111111111111111111111111111");
            Query query = em.createQuery("select mes from Message mes where mes.name = :name");
            query.setParameter("name",loginname);
            List list = query.getResultList();
            if (list.size() != 0) {
                for (Object i : list) {
                    message = (Message) i;
                    if (message.getname().equals(loginname)&&message.getpassword().equals(loginpassword)) {
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                req.getSession().setAttribute("LocalUser", message);
                resp.sendRedirect("/usercenter.jsp");
            } else {
                System.out.println("该用户不存在，请先注册");
                resp.sendRedirect("/error.jsp");
            }
        }catch(Exception e)
        {
            resp.sendRedirect("/error.jsp");
        }finally {
            em.close();
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        login_check(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
